package sdf

import (
	"ErgodicBorder/border"
	"math"
	"sync"
)

var wg sync.WaitGroup

// GenerateSDF 获取sdf
func GenerateSDF(width, length int, borders []*border.BorderBlock, masks [][]bool) [][]float64 {
	sdf := make([][]float64, len(masks))
	for i := 0; i < width; i++ {
		wg.Add(1)
		go func(i int) {
			defer wg.Done()
			arr := make([]float64, length)
			for j := 0; j < length; j++ {
				arr[j] = computeSDF(float64(j), float64(i), float64(length), float64(width), borders, !masks[i][j])
			}
			sdf[i] = arr
		}(i)
	}
	wg.Wait()
	return sdf
}

// 计算sdf的值
func computeSDF(x, y, length, width float64, borders []*border.BorderBlock, isMask bool) float64 {
	a := x / length
	b := y / width
	a2b2 := a*a + b*b
	var _min, temp float64
	_min = math.Inf(1)
	for _, p := range borders {
		distance := p.NormalizeX2y2 + a2b2 - p.Normalize2x*a - p.Normalize2y*b
		temp = math.Sqrt(distance)
		_min = Min(_min, temp)
	}
	if isMask {
		_min *= -1
	}
	//归一化距离
	return _min / math.Sqrt2
}

func Min(a, b float64) float64 {
	if a < b {
		return a
	}
	return b
}
